//
//  ViewController.swift
//  Md5Compare
//
//  Created by mx004 on 17/11/24.
//  Copyright © 2017年 mx004. All rights reserved.
//

import Cocoa

struct md5Info {
    var filePath:String
    var md5Value:String
    
}

class ViewController: NSViewController {
    @IBOutlet var optxt: NSTextView!

    @IBOutlet weak var okbtn: NSButton!
    @IBOutlet weak var md5dir1: NSTextField!
    @IBOutlet weak var md5dir2: NSTextField!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        md5dir1.stringValue = RecordModel.shared.dir1
        md5dir2.stringValue = RecordModel.shared.dir2
        
        md5dir1.register(forDraggedTypes: ["*.*"])
        md5dir2.register(forDraggedTypes: ["*.*"])
    }

    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }
    
    @IBAction func clickCompareButton(_ sender: Any) {
        //let dir1 = "/Users/mx004/Documents/build_ios"
        //let dir2 = "/Users/mx004/Documents/build_ios/bin"
        
        let dir1 = md5dir1.stringValue
        let dir2 = md5dir2.stringValue
        if dir1 == "" {
            optxt.string = "dir1 is not null~~~";
            return
        }
        if dir2 == "" {
            optxt.string = "dir2 is not null ~~";
            return
        }
        optxt.string = "正在处理中..."
        
        RecordModel.shared.save(dir1: dir1, dir2: dir2)
        
//        findFiles(path: dir1).forEach { (str) in
//            print(str)
//            print(fileMD5(str)!)
//            
//        }
        
        okbtn.title = "正在处理中";
        okbtn.isEnabled = false
        
        
        CompareDir(dir1:dir1,dir2:dir2){[weak self](cf,f1,f2) in
            let maxCount = f1 > f2 ? f1 : f2;
            var strout = "文件对比完成...\n"
            strout += "总文件数: dir1:\(f1), dir2: \(f2)\n"
            strout += "重复文件数:\(cf) \n";
            strout += "占比:\(String(format:"%.2f",(Double(cf) /  Double(maxCount) * 100.0)))%";
            
            
            self?.optxt.string = strout;
            self?.okbtn.title = "对比文件";
            self?.okbtn.isEnabled = true

        }

        
    }

    func CompareDir(dir1:String,dir2:String,complete:((_ cf:Int,_ f1:Int,_ f2:Int)->Void)?) {
        DispatchQueue.global().async {
            var dirMap1:[String:String] = [String:String]()
            for str in findFiles(dir1) {
                dirMap1[str] = fileMd5(str)
            }
            
            var dirMap2:[String:String] = [String:String]()
            for str in findFiles(dir2) {
                dirMap2[str] = fileMd5(str)
            }
            
            
            var cfcount = 0
            for v in dirMap2 {
                for vv in dirMap1 {
                    if v.value == vv.value {
                        cfcount  = cfcount + 1
                    }
                }
            }

            DispatchQueue.main.async(execute: {()->() in
                if complete != nil {complete!(cfcount,dirMap1.count,dirMap2.count)}
            })
        }
    }
    
    
    
 

}

extension String{
    func md5() ->String!{
        let str = self.cString(using: String.Encoding.utf8)
        let strLen = CUnsignedInt(self.lengthOfBytes(using: String.Encoding.utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        CC_MD5(str!, strLen, result)
        let hash = NSMutableString()
        for i in 0 ..< digestLen {
            hash.appendFormat("%02x", result[i])
        }
        result.deinitialize()
        return String(format: hash as String)
    }
}

